﻿@namespace Masa.Docs.Shared.Components

@inject IJSRuntime Js
@inject I18n I18n

<div id="docsearch" class="mr-2 @Display"></div>

@code {

    [CascadingParameter(Name = "Env")]
    public string? Env { get; set; }

    [Parameter]
    public Project? Project { get; set; }

    [Parameter]
    public string? Class { get; set; }

    [Parameter]
    public string? Style { get; set; }

    private Project? _prevProject;

    private string Display => Project?.IsValid is not true ? "d-none" : string.Empty;

    protected override void OnParametersSet()
    {
        base.OnParametersSet();

        if (_prevProject != Project)
        {
            _prevProject = Project;

            if (Project?.IsValid is true)
            {
                _ = InitDocSearchAsync();
            }
        }
    }

    public async ValueTask InitDocSearchAsync()
    {
        try
        {
            if (Project?.IsValid is not true) return;
            var currentLanguage = I18n!.Culture.TwoLetterISOLanguageName;
            var indexName = Env + I18n.Culture.TwoLetterISOLanguageName + "_" + Project.Key;
            await Js.InvokeVoidAsync("addDocSearch", indexName, currentLanguage, I18n.T("Search"));
        }
        catch
        {
            // ignored
        }
    }

}
